package com.ruoyi.business.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.enums.OrderStatus;
import com.ruoyi.business.response.ResponseData;
import com.ruoyi.business.service.BasePayment;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.HttpResponse;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.common.utils.MoneyUtil;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;

@Service("yyhPayService")
public class YyhPayServiceImpl extends BasePayment {

    @Override
    public JSONObject createPayOrder(TOrderInfo orderInfo) throws Exception {
        JSONObject jsonObject = new JSONObject();
        TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
        HashMap<String, String> headerMap = new HashMap();
        HashMap<String, String> dataMap = new HashMap();
        String cookieStr = userRecipientInfo.getCookie();
        JSONObject cookieObj = JSONObject.parseObject(cookieStr);
        String qrcode = userRecipientInfo.getReceiptQrcode();
//        String qrcode_ = HttpUtils.getParam(qrcode,"userAppId");
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


//
//        String url = "https://api.umvtech.com/api/payment/getUserName";
//        dataMap.put("user_code",userRecipientInfo.getPhoneNo());
//        HttpResponse priceHttpResponse = HttpUtils.httpFormPost(url,headerMap,"",dataMap,"kiss查询用户请求","");
//        JSONObject resultObj = JSONObject.parseObject(priceHttpResponse.getDocument().body().text());
//        int resultCode = resultObj.getInteger("status");
//        String priceId = "";
//        if(resultCode==1){
//
//
//
//        }
        //https://qr.leshuazf.com/pay/qrc.do?qr=SYTD200387629
        //https://wap.yiyinpay.com/#/pageInit/pay?key=a1ec088249e4294fe9442c59e3f039ce

        String token = sysConfigService.selectConfigByKey("IP_138_TOKEN");

        String[]  adds =  commonService.getAddresBy138Ip(orderInfo.getOutBody(),token);
        String proxyIp = "";
        if(adds!=null){
            logger.info("ip定位地址："+adds[1]+""+adds[2]);
            JSONObject ipObj = commonService.getPoxyIp(adds[1],adds[2]);
            if(ipObj.getString("code").equals("200")){
                proxyIp = ipObj.getString("ip")+":"+ipObj.getString("port");
            }
        }
        logger.info("请求代理："+proxyIp);

        headerMap.put("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 17_1_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/21B101 Ariver/1.1.0 AliApp(AP/10.5.55.6000) Nebula WK RVKType(1) AlipayDefined(nt:WIFI,ws:390|780|3.0) AlipayClient/10.5.55.6000 Alipay Language/zh-Hans Region/CN NebulaX/1.0.0");

        //https://test-pay.52pay.com/api/preQrcode/2078
//        logger.info("qrcode："+cookieObj.getString("userId"));

//        String url ="https://test-pay.52pay.com/api/preQrcode/2078";
        logger.info("收银台HTMLurl："+qrcode);
        String key = getParamByUrl(qrcode,"key");
        headerMap.put("shop_id",key);
        headerMap.put("anti","@#fdd");
        headerMap.put("platform","ios");
        headerMap.put("model","iPhone");
        headerMap.put("Origin","https://wap.yiyinpay.com");
        headerMap.put("Referer","https://wap.yiyinpay.com");

        dataMap = new HashMap();
        dataMap.put("key",key);
        dataMap.put("subject","%E6%94%AF%E4%BB%98%E4%BB%98%E6%AC%BE");
        dataMap.put("money", MoneyUtil.fenToYuan(orderInfo.getMoney()+""));
        dataMap.put("user_id","0");
        dataMap.put("payment_type","2");
        dataMap.put("is_weixin","false");
        dataMap.put("wx_code","");
        dataMap.put("channel_id","0");
        dataMap.put("buyer_id","0");
        String getOrderUrl = "https://api.yiyinpay.com:9500/m/Index/payBill";
        HttpResponse httpResponse = HttpUtils.httpFormPost(getOrderUrl,headerMap,"",dataMap,"YYH",proxyIp);
        logger.info("YYH请求返回的:"+httpResponse);

        JSONObject orderNoObj = JSONObject.parseObject(httpResponse.getBody());
        if(orderNoObj.getIntValue("code")!=200){
            jsonObject.put("code","100");
            jsonObject.put("msg","获取连接失败");
            logger.info("========KMT修改收款账号为不可用===============");
            userRecipientInfo.setChannelDisabled(1);
            userRecipientService.updateTRecipientInfo(userRecipientInfo);
            return jsonObject;
        }
        JSONObject jspay_info = orderNoObj.getJSONObject("result");
        String order_sn = jspay_info.getString("order_sn");
        String getPayUrl = "https://api.yiyinpay.com:9500/m/Index/payOnline?order_sn="+order_sn+"&payment_code=alipay_scan&open_id=&store_pay=1";
        HttpResponse payResponse = HttpUtils.httpFormGet(getPayUrl,headerMap,"","KMT",proxyIp);
        JSONObject payObj = JSONObject.parseObject(payResponse.getBody());
        if(payObj.getIntValue("code")!=200){
            jsonObject.put("code","100");
            jsonObject.put("msg","获取连接失败");
            logger.info("========KMT修改收款账号为不可用===============");
            userRecipientInfo.setChannelDisabled(1);
            userRecipientService.updateTRecipientInfo(userRecipientInfo);
            return jsonObject;
        }
        JSONObject resultObj = orderNoObj.getJSONObject("result");

        String payUrl = resultObj.getString("qr_code");

//
//        String aliNo = payUrl.split("alipayTradeNo\":\"")[1].split("\"}")[0];
        orderInfo.setStatus(OrderStatus.WAIT_PAY.getCode());
        orderInfo.setQrcodeTxt(cookieObj.toJSONString());
        orderInfoService.updateTOrderInfo(orderInfo);
        jsonObject.put("payUrl",payUrl);
        jsonObject.put("orderNo",order_sn);
        jsonObject.put("code","200");
        return jsonObject;
    }

    public JSONObject createWxPayOrder(TOrderInfo orderInfo) throws ServiceException, UnsupportedEncodingException {
        JSONObject jsonObject = new JSONObject();
        TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
        HashMap<String, String> headerMap = new HashMap();
        HashMap<String, String> dataMap = new HashMap();
        String cookieStr = userRecipientInfo.getCookie();
        JSONObject cookieObj = JSONObject.parseObject(cookieStr);


        String proxyIp =orderInfo.getProxyIp();

        headerMap.put("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 15_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.22(0x18001627) NetType/4G Language/zh_CN");


        logger.info("qrcode："+cookieObj.getString("userId"));

        String url ="https://shop.shouyinbei.net/app/wxapp.php?i=1&v=undefined&m=we7_wmall&c=entry&do=mobile&ctrl=wmall&ac=store&op=paybill&ta=getNewStoreInfo&from=wxapp&state=we7sid-1f5947214065a723ec571946828f80ac&code_id="+cookieObj.getString("userId")+"&type=2&is_pay=1&sid=undefined";
        logger.info("收银台HTMLurl："+url);

        HttpResponse httpResponse = HttpUtils.httpFormGet(url,headerMap,"","SYB",proxyIp);
        logger.info("返回的HTML:"+httpResponse.getDocument().text());
        JSONObject storeIdObj = JSONObject.parseObject(httpResponse.getDocument().text());

        String storeId = storeIdObj.getJSONObject("message").getString("store_id");
//        url ="https://shop.shouyinbei.net/app/wxapp.php?i=1&v=undefined&m=we7_wmall&c=entry&do=mobile&ctrl=wmall&ac=store&op=paybill&ta=index&from=wxapp&state=we7sid-1f5947214065a723ec571946828f80ac&sid="+storeId+"&total_fee="+MoneyUtil.fenToYuan(orderInfo.getMoney()+"")+"&no_discount_part=0&discount_amt=0&couponId=false&note=&is_pay=1&province=";
//        logger.info("收银台HTMLurl："+url);
//
//        httpResponse = HttpUtils.httpFormGet(url,headerMap,"","SYB",proxyIp);
//        logger.info("预生成的微信订单号:"+httpResponse.getDocument().text());
//        JSONObject perOrderObj = JSONObject.parseObject(httpResponse.getDocument().text());
//
//        String perOrderId = perOrderObj.getJSONObject("message").getString("message");
//        url = "https://shop.shouyinbei.net/app/wxapp.php?i=1&v=undefined&m=we7_wmall&c=entry&do=mobile&ctrl=system&ac=paycenter&op=pay&from=wxapp&state=we7sid-1f5947214065a723ec571946828f80ac&pay_type=new_wechat&order_type=paybill&id="+perOrderId+"&pay_type2=0&province=&city=&nickName=&avatar=&snNo=&order_source=&note=";
//        httpResponse = HttpUtils.httpFormGet(url,headerMap,"","SYB",proxyIp);
//        JSONObject payOrderObj = JSONObject.parseObject(httpResponse.getDocument().text());
//        String payAppId = payOrderObj.getJSONObject("message").getJSONObject("message").toJSONString();


        dataMap = new HashMap();
        dataMap.put("storeId",storeId);
        dataMap.put("merchantCode",cookieObj.getString("merchantCode"));
        dataMap.put("userId",orderInfo.getAliUserId());
        dataMap.put("userAppId",cookieObj.getString("userId"));
        dataMap.put("payWay","WXZF");
        dataMap.put("comsumeMoney", MoneyUtil.fenToYuan(orderInfo.getMoney()+""));
        url = "https://www.shouyinbei.net/wap/merchant/tradePay";
        logger.info("下单URL："+url);
        StringBuilder buf = new StringBuilder("");
        HttpUtils.buildPayParams(buf, dataMap);
        String preStr = buf.toString();
        logger.info("请求参数："+preStr);

        //headerMap.put("Referer","https://www.shouyinbei.net/wap/merchant/h5pay?auth_code="+orderInfo.getAliAuthCode()+"&userAppId="+cookieObj.getString("userId"));

//        HttpResponse payHttpResponse = HttpUtils.httpFormPost(url,headerMap,"",dataMap,"SYB下单",proxyIp);
        String payHttpResponse = HttpUtils.sendPostRequestByProxyIp(url,preStr,headerMap,proxyIp);

        logger.info("syb请求返回的:"+payHttpResponse);

        JSONObject payInforesultObj = JSONObject.parseObject(payHttpResponse);
        if(payInforesultObj.getIntValue("code")!=200){
            jsonObject.put("code","100");
            jsonObject.put("msg","获取连接失败");
            return jsonObject;
        }
        JSONObject jspay_info = payInforesultObj.getJSONObject("data");
        String tradeNO = jspay_info.toJSONString();
//        JSONObject payInfoObj = new JSONObject();
//        payInfoObj.put("appid",payInforesultObj.getString("appid"));
//        payInfoObj.put("merchant_id",payInforesultObj.getString("merchant_id"));
//        payInfoObj.put("qrcode",qrcode_);
//        payInfoObj.put("order_id",payInforesultObj.getString("order_id"));
//        payInfoObj.put("notify_key",payInforesultObj.getString("notify_key"));
//        payInfoObj.put("third_order_id",payInforesultObj.getString("third_order_id"));
//        orderInfo.setQrcodeTxt(payInfoObj.toJSONString());
//        orderInfoDao.update(orderInfo);
        orderInfo.setQrcodeTxt(cookieObj.toJSONString());
        orderInfoService.updateTOrderInfo(orderInfo);
        jsonObject.put("payUrl",tradeNO);
        jsonObject.put("orderNo",jspay_info.getString("orderNumber"));
        jsonObject.put("code","200");
        return jsonObject;
    }
    @Override
    public ResponseData smartReissueOrder(TOrderInfo orderInfo) throws Exception {
        return new ResponseData();
    }

}
